<template>
  <div class="position-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <div class="stats-card">
          <div class="stats-icon">
            <i class="el-icon-suitcase"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">0</div>
            <div class="stats-label">总仓位数</div>
          </div>
          <div class="stats-change">+0</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stats-card">
          <div class="stats-icon money">
            <i class="el-icon-money"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">$0.00</div>
            <div class="stats-label">总盈亏</div>
          </div>
          <div class="stats-rate success">0.00%</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stats-card">
          <div class="stats-icon chart">
            <i class="el-icon-data-line"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">$0.00</div>
            <div class="stats-label">浮动盈亏</div>
          </div>
          <div class="stats-rate success">0.00%</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stats-card">
          <div class="stats-icon shield">
            <i class="el-icon-warning"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">$0.00</div>
            <div class="stats-label">已用保证金</div>
          </div>
          <div class="stats-rate">0%</div>
        </div>
      </el-col>
    </el-row>

    <!-- 仓位分布 -->
    <div class="distribution-section">
      <div class="section-header">
        <div class="title">仓位分布</div>
        <div class="view-toggle">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button label="distribution">分布图</el-radio-button>
            <el-radio-button label="list">盈亏图</el-radio-button>
            <el-radio-button label="trend">趋势图</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="chart-container" ref="distributionChart"></div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-container">
      <div class="filter-row">
        <div class="status-tabs">
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'all' }"
            @click="filterStatus = 'all'"
          >
            <span>全部</span>
            <el-badge :value="0" class="status-count" type="primary" />
          </div>
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'profit' }"
            @click="filterStatus = 'profit'"
          >
            <span>多头</span>
            <el-badge :value="0" class="status-count" />
          </div>
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'loss' }"
            @click="filterStatus = 'loss'"
          >
            <span>空头</span>
            <el-badge :value="0" class="status-count" />
          </div>
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'waiting' }"
            @click="filterStatus = 'waiting'"
          >
            <span>等撤</span>
            <el-badge :value="0" class="status-count" />
          </div>
        </div>
      </div>

      <div class="filter-row">
        <div class="filter-group">
          <div class="filter-item">
            <el-select v-model="filterExchange" placeholder="全部交易所" size="small">
              <el-option label="全部交易所" value="all" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-input
              v-model="searchPair"
              placeholder="搜索交易对..."
              prefix-icon="el-icon-search"
              size="small"
            />
          </div>
          <div class="filter-item">
            <el-select v-model="filterStrategy" placeholder="全部策略" size="small">
              <el-option label="全部策略" value="all" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="filterRisk" placeholder="全部风险" size="small">
              <el-option label="全部风险" value="all" />
            </el-select>
          </div>
        </div>
        <el-button 
          type="primary" 
          icon="el-icon-refresh" 
          size="small"
          @click="resetFilters"
          class="reset-button"
        >重置筛选</el-button>
      </div>
    </div>

    <!-- 持仓列表 -->
    <div class="position-table">
      <el-table
        :data="positionList"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="pair" label="交易对" sortable />
        <el-table-column prop="direction" label="方向" width="80">
          <template slot-scope="scope">
            <span :class="scope.row.direction === 'long' ? 'long-text' : 'short-text'">
              {{ scope.row.direction === 'long' ? '多' : '空' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="仓位大小" sortable />
        <el-table-column prop="openPrice" label="开仓价格" sortable />
        <el-table-column prop="markPrice" label="标记价格" sortable />
        <el-table-column prop="margin" label="保证金" sortable />
        <el-table-column prop="marginRate" label="保证金率" sortable />
        <el-table-column prop="exchange" label="交易所" />
        <el-table-column prop="strategy" label="策略" />
        <el-table-column prop="risk" label="风险" />
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small">平仓</el-button>
            <el-button type="text" size="small">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'PositionManagement',
  data() {
    return {
      // 视图模式
      viewMode: 'distribution',
      
      // 筛选条件
      filterStatus: 'all',
      filterExchange: 'all',
      searchPair: '',
      filterStrategy: 'all',
      filterRisk: 'all',

      // 表格数据
      loading: false,
      positionList: [],

      // 图表实例
      charts: {
        distribution: null
      },

      // 模拟数据
      mockPositions: [
        {
          id: 1,
          pair: 'BTC/USDT',
          direction: 'long',
          size: '0.5',
          openPrice: '45,280.50',
          markPrice: '45,380.20',
          margin: '2,264.02',
          marginRate: '20x',
          exchange: 'Binance',
          strategy: '趋势跟踪A',
          risk: '中等'
        },
        {
          id: 2,
          pair: 'ETH/USDT',
          direction: 'short',
          size: '5.0',
          openPrice: '2,850.25',
          markPrice: '2,845.80',
          margin: '1,425.12',
          marginRate: '10x',
          exchange: 'OKX',
          strategy: '网格交易B',
          risk: '低'
        },
        {
          id: 3,
          pair: 'BNB/USDT',
          direction: 'long',
          size: '10',
          openPrice: '320.80',
          markPrice: '322.50',
          margin: '1,604.00',
          marginRate: '5x',
          exchange: 'Binance',
          strategy: '套利策略C',
          risk: '高'
        }
      ]
    }
  },
  methods: {
    resetFilters() {
      this.filterStatus = 'all'
      this.filterExchange = 'all'
      this.searchPair = ''
      this.filterStrategy = 'all'
      this.filterRisk = 'all'
      this.fetchPositions()
    },
    fetchPositions() {
      this.loading = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        // 根据筛选条件过滤持仓
        let filteredPositions = [...this.mockPositions]
        
        // 状态筛选
        if (this.filterStatus !== 'all') {
          filteredPositions = filteredPositions.filter(position => {
            if (this.filterStatus === 'profit') return position.direction === 'long'
            if (this.filterStatus === 'loss') return position.direction === 'short'
            return false
          })
        }

        // 交易所筛选
        if (this.filterExchange !== 'all') {
          filteredPositions = filteredPositions.filter(position => 
            position.exchange.toLowerCase() === this.filterExchange
          )
        }

        // 搜索交易对
        if (this.searchPair) {
          const keyword = this.searchPair.toLowerCase()
          filteredPositions = filteredPositions.filter(position => 
            position.pair.toLowerCase().includes(keyword)
          )
        }

        // 策略筛选
        if (this.filterStrategy !== 'all') {
          filteredPositions = filteredPositions.filter(position => 
            position.strategy === this.filterStrategy
          )
        }

        // 风险筛选
        if (this.filterRisk !== 'all') {
          filteredPositions = filteredPositions.filter(position => 
            position.risk === this.filterRisk
          )
        }

        this.positionList = filteredPositions
        this.loading = false
        
        // 更新图表
        this.updateChart()
      }, 500)
    },
    initCharts() {
      if (this.$refs.distributionChart) {
        this.charts.distribution = echarts.init(this.$refs.distributionChart)
        this.updateChart()
      }
    },
    updateChart() {
      if (!this.charts.distribution) return

      // 根据视图模式显示不同的图表
      let option = {}
      
      if (this.viewMode === 'distribution') {
        // 仓位分布图配置
        const exchangeData = {}
        this.positionList.forEach(position => {
          if (!exchangeData[position.exchange]) {
            exchangeData[position.exchange] = {
              long: 0,
              short: 0
            }
          }
          if (position.direction === 'long') {
            exchangeData[position.exchange].long += parseFloat(position.size)
          } else {
            exchangeData[position.exchange].short += parseFloat(position.size)
          }
        })

        const exchanges = Object.keys(exchangeData)
        option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['多头', '空头']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value'
          },
          yAxis: {
            type: 'category',
            data: exchanges
          },
          series: [
            {
              name: '多头',
              type: 'bar',
              stack: 'total',
              label: {
                show: true
              },
              emphasis: {
                focus: 'series'
              },
              data: exchanges.map(exchange => exchangeData[exchange].long)
            },
            {
              name: '空头',
              type: 'bar',
              stack: 'total',
              label: {
                show: true
              },
              emphasis: {
                focus: 'series'
              },
              data: exchanges.map(exchange => -exchangeData[exchange].short)
            }
          ]
        }
      } else if (this.viewMode === 'list') {
        // 盈亏分布图配置
        // TODO: 实现盈亏分布图
      } else if (this.viewMode === 'trend') {
        // 趋势图配置
        // TODO: 实现趋势图
      }

      this.charts.distribution.setOption(option)
    },
    handleResize() {
      if (this.charts.distribution) {
        this.charts.distribution.resize()
      }
    }
  },
  watch: {
    viewMode() {
      this.updateChart()
    },
    filterStatus() { this.fetchPositions() },
    filterExchange() { this.fetchPositions() },
    searchPair() { this.fetchPositions() },
    filterStrategy() { this.fetchPositions() },
    filterRisk() { this.fetchPositions() }
  },
  mounted() {
    this.fetchPositions()
    this.$nextTick(() => {
      this.initCharts()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.charts.distribution) {
      this.charts.distribution.dispose()
    }
  }
}
</script>

<style lang="scss" scoped>
.position-container {
  padding: 20px;
  background-color: #f5f7fa;

  .stats-row {
    margin-bottom: 20px;

    .stats-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      height: 100px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      display: flex;
      align-items: center;
      position: relative;

      .stats-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        background-color: #409EFF;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        i {
          font-size: 24px;
          color: #fff;
        }

        &.money {
          background-color: #67C23A;
        }

        &.chart {
          background-color: #E6A23C;
        }

        &.shield {
          background-color: #F56C6C;
        }
      }

      .stats-info {
        flex: 1;

        .stats-value {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
          margin-bottom: 8px;
        }

        .stats-label {
          font-size: 14px;
          color: #909399;
        }
      }

      .stats-change,
      .stats-rate {
        position: absolute;
        top: 20px;
        right: 20px;
        font-size: 14px;
        color: #909399;

        &.success {
          color: #67C23A;
        }

        &.danger {
          color: #F56C6C;
        }
      }
    }
  }

  .distribution-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .chart-container {
      height: 300px;
    }
  }

  .filter-container {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .filter-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      .status-tabs {
        display: flex;
        gap: 8px;
        
        .status-tab {
          padding: 6px 12px;
          border-radius: 4px;
          cursor: pointer;
          display: flex;
          align-items: center;
          gap: 6px;
          background-color: #f5f7fa;
          transition: all 0.3s;
          font-size: 13px;
          
          &:hover {
            background-color: #ecf5ff;
          }
          
          &.active {
            background-color: #409EFF;
            color: #fff;
            
            .el-badge__content {
              background-color: #fff !important;
              color: #409EFF !important;
            }
          }
          
          .status-count {
            transform: scale(0.8);
          }
        }
      }

      .filter-group {
        display: flex;
        gap: 8px;

        .filter-item {
          .el-select,
          .el-input {
            width: 140px;
          }
        }
      }

      .reset-button {
        height: 32px;
        margin-left: 8px;
      }
    }
  }

  .position-table {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .long-text {
      color: #67C23A;
    }

    .short-text {
      color: #F56C6C;
    }
  }
}
</style> 